<?php

/*

	Copyright © 2011 Mike Bennett <mike@kereru.com>

	This file is part of Tazu-Time.

    Tazu-Time is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    Tazu-Time is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Tazu-Time.  If not, see <http://www.gnu.org/licenses/>.
    
*/


class timesheet_win extends win_gtk {


	var $trayicon = FALSE;						// GTKStatusIcon object
	var $minimised = FALSE;						// Minimised to system tray

	var $actions = array();						// List of possible actions that can be done in trayicon
	

	public $win_name = 'timesheet';
	public $win_icon = WINDOW_ICON;
	public $win_title = APPNAME;
	
	public $statusbar = FALSE;					// Statusbar control
	public $statusbar_text=array();				// Statusbar test stored so can be resized

	public $control=array();					// All controls

	// Timesheet specific
	var $timer_running=FALSE;
	var $clock_on = FALSE;						// Flashing clock
	var $timer_elapsed=0;
	var $start_time = FALSE;
	
	var $cust_name='';							// Display formatted customer name
	var $task_name='';							// Display formatted task name
	
	
	var $timesheets = FALSE;					// Full path to current timesheets file in use
	var $customers = FALSE;						// Full path to customers db file.
	
	var $data_types = FALSE;					// List of data types that can be attached to sessions
	var $xlate = FALSE;							// All text translations
	
/*
	var $xlate_controls = array(
								'select_customer_frame_label',
								'ts_new_lbl',
								'ts_edit_lbl',
								'ts_delete_lbl'
	
								);				// List of controls and labels to have text translations
	
*/

//	var $tools_id = 180;						// Starting id for tools menu
	

	function __construct() {
		global $gl, $argv;
		
		$this->const_base = 10100;
		$this->make_constants();
		
		// Check for any command line params
		$cl = new Args();
		$setup_cmd = $cl->flag('setup_cmd');
		unset($cl);
		
		if ( $setup_cmd <> '' ) {
			// Called from the setup installer with the command line params --setup_cmd={setup command path}
			// Used beacuse renamed setup progs can trigger different program branding
		
			$path_parts = pathinfo($setup_cmd);
		
			if ( $path_parts['filename'] == 'Tazu-Timesheet-hyperlink-setup' ) {

				// Set the branding for hyperlink
				$cnf = new conf_timesheet(INIFILE);
				$cnf->set_value('BRAND','name','hyperlink');		
				$cnf->set_value('BRAND','logo_32','hl_32.png');		
				$cnf->set_value('BRAND','logo_tooltip','Hyperlink web site.');		
				$cnf->set_value('BRAND','logo_url','http://hyperlink.net.nz');		
				$cnf->save_ini();
			}

			die;
		}



	}


	// 
	/**
	*	
	*	
	*	@param	
	*	@return	
	*	
	*/
	function customers() {
		global $gl;
		
		$customer_id = $this->selected_customer();
				
		if ( $customer_id ) {

			// Customer selected
			$customer_name = $this->control['ts_customers']->get_selected('name');
				
			// Load the Time Sheet frame
			$this->entry_list_draw($customer_id);				
				
			// Load the Project/Task frame
			$this->project_list_draw($customer_id);				
				
			// Enable appropriate timer tools at bottom
			$this->enable_customer($customer_id);

					
			// Reports
			// All customers checkbox
			$this->control['ts_all_customers']->set_checked(FALSE);
			$this->enable_report_list();
					
					
		}
		else {
			// No selection
			$this->resetControls();				

			// All customers checkbox
			$this->control['ts_all_customers']->set_checked(TRUE);
		}
				
	
	}
	



	/**
	*	Populate the customer list
	*	
	*	@param	
	*	@return	
	*	
	*/
	function customer_list_draw($customer_id=FALSE) {

		$ts = new Customers($this->customers);
		$customers = $ts->getCustomers();
		$ts->close();
		unset( $ts);
		
		$this->control['ts_customers']->clear();

		foreach ( $customers as $idx => $dat ) {
			$row_dat = array( $dat['id'], $dat['name'], $dat['company'] );
			$this->control['ts_customers']->append($row_dat);
		}

//$this->control['ts_customers']->widget->set_grid_lines(Gtk::TREE_VIEW_GRID_LINES_VERTICAL); 

		if ( $customer_id ) {
			// Make this customer selected as well
			$this->control['ts_customers']->set_selected('id',$customer_id);
		}



	}

	function clock() {

		$this->set_status( date("  d/m/Y  H:i",$this->time_offset(mktime())) ,2);
		return(TRUE);
	}

	function clock_flasher() {

		if ( ! $this->timer_running ) return(TRUE);


		// Flash the window icon ( for when minimised )
//		wb_set_image($secwin, PATH_RES . ($state ? "ttf.ico" : "hyper.ico"));

	
		// Flash the clock	
		if ( $this->clock_on ) {
//			$this->win->set_title('<span forground="#FF0000">'.$this->task_name.'</span>');

			$hh = $this->control['ts_hour']->get_text();
			$mm = $this->control['ts_min']->get_text();

			$this->win->set_title(sprintf("%02d:%02d %s",$hh,$mm,$this->task_name));


///			wb_set_image($this->win, PATH_RES ."blank.ico");
//			$this->set_text('ts_timer_label','<span foreground="#FFA26D" weight="bold">Timer</span>');
			$this->control['ts_timer_label']->set_text('<span foreground="#FF0000" weight="bold">Timer</span>');
//			$this->invisible(TS_TIMER_BG,$this->tabs);
		}
		else {
			$this->win->set_title(APPSHORTNAME.' '.VER.'.'.BUILD);

///			wb_set_image($this->win, PATH_RES ."timesheet.ico");
//			$this->set_text('ts_timer_label','<span foreground="#FF5D00" weight="bold">Stop</span>');
			$this->control['ts_timer_label']->set_text('<span foreground="#FF0000" weight="bold">Stop</span>');

//			$this->visible(TS_TIMER_BG,$this->tabs);
		}


		$this->clock_on = ! $this->clock_on;

		return(TRUE);
				
	}


	function display_timer_running() {

//*		wb_set_text($this->win, APPNAME.' (Timer Running)');
//*		wb_set_image($this->win, PATH_RES ."timesheet.ico");

		$this->clock_on = TRUE;
		
		$this->enable('TS_TIMER');

		$this->enable('TS_SAVE_B');				// Allows save of comments

//*		$this->set_text(TS_TIMER,'Stop',$this->tabs);

		$this->disable('TS_ENTRIES');
		$this->disable('TS_ADD_SESSION');
		$this->disable('TS_DELETE_B');
		$this->disable('TS_ENTRY_TASK');
		$this->disable('TS_ENTRY_DATE');
		$this->disable('TS_START_PREV');
		$this->disable('TS_HOUR_START');
		$this->disable('TS_MIN_START');
		$this->disable('TS_ELAPSED_NOW');
		$this->disable('TS_HOUR');
		$this->disable('TS_MIN');
		$this->disable('TS_CUSTOMERS');
		$this->disable('TS_NEW');
		$this->disable('TS_EDIT');
		$this->disable('TS_DELETE');
		$this->disable('PROJ_LIST');
		$this->disable('PROJ_NEW');
		$this->disable('PROJ_EDIT');
		$this->disable('PROJ_DELETE');
//		$this->disable('TS_CUSTOMERS_FRAME');
//		$this->disable('PROJ_FRAME');
	}

	function display_timer_stopped() {
		global $gl;

//*		wb_set_text($this->win, APPNAME);
//*		wb_set_image($this->win, PATH_RES ."timesheet.ico");

		$this->clock_on = FALSE;
		$this->enable('TS_TIMER');
//*		$this->set_text(TS_TIMER,'Start',$this->tabs);

		$this->enable('TS_ENTRIES');
		$this->enable('TS_ADD_SESSION');
		$this->enable('TS_DELETE_B');
		$this->enable('TS_SAVE_B');
		$this->enable('TS_ENTRY_TASK');
		$this->enable('TS_ENTRY_DATE');
		$this->enable('TS_START_PREV');
		$this->enable('TS_HOUR_START');
		$this->enable('TS_MIN_START');
		$this->enable('TS_ELAPSED_NOW');
		$this->enable('TS_HOUR');
		$this->enable('TS_MIN');
		$this->enable('TS_CUSTOMERS');
		$this->enable('TS_NEW');
		$this->enable('TS_EDIT');
		$this->enable('TS_DELETE');
		$this->enable('PROJ_LIST');
		$this->enable('PROJ_NEW');
		$this->enable('PROJ_EDIT');
		$this->enable('PROJ_DELETE');
//		$this->enable('TS_CUSTOMERS_FRAME');
//		$this->enable('PROJ_FRAME');
	}



	
	function projects() {

//		$sel_cust = wb_get_selected(wb_get_control($this->win,TS_CUSTOMERS));
//		$sel_proj = wb_get_selected(wb_get_control($this->win,PROJ_LIST));

		$task_id = $this->selected_task();
		if ( $task_id ) {
			// Task selected
			$task_code = $this->control['proj_list']->get_selected('task_code');
			$task_name = $this->control['proj_list']->get_selected('task');
			$this->task_name = $this->control['proj_list']->get_selected('task');

			$this->enable('TS_ADD_SESSION');
			$this->enable('PROJ_NEW');
			$this->enable('PROJ_EDIT');
			$this->enable('PROJ_DELETE');
			
		}
		else {
			// no tasks selected
			$this->task_name = '';
			$this->disable('TS_ADD_SESSION');
			$this->enable('PROJ_NEW');
			$this->disable('PROJ_EDIT');
			$this->disable('PROJ_DELETE');
		}

		$customer_id = $this->selected_customer();
		if ( $customer_id ) {
			// Customer Selected
			$customer_name = $this->control['ts_customers']->get_selected('name');
				
			// Load the Project/Task frame
//			$this->enable('PROJ_FRAME');
			$this->enable('PROJ_LIST');
		}
		else {
			// No customer selected		
			$this->cust_name = '';
			$this->disable('TS_ADD_SESSION');
		}

		$this->show_project();
	
	}

	

	/**
	*	Populate the project list
	*	
	*	@param	
	*	@return	
	*	
	*/
	function project_list_draw($customer_id,$task_id=FALSE) {

		$ts = new Timesheet($this->timesheets,$this->customers);
		$projects = $ts->getProjects($customer_id);
		$ts->close();
		unset( $ts);

		$this->control['proj_list']->clear();

		foreach ( $projects as $idx => $dat ) {
			$row_dat = array( $dat['id'], $dat['task_code'], $dat['task'], $dat['estimate_time'], $dat['elapsed'] );
			$this->control['proj_list']->append($row_dat);
		}

		// Make this task/project selected as well
		$this->project_list_selected($customer_id ,$task_id );

	}

	function project_list_selected($customer_id,$task_id=FALSE) {

		if ( $task_id ) {
			$this->control['proj_list']->set_selected('id',$task_id);
		}

		$this->listview_drawn['projects'] = TRUE;

	}



	function entry_list_draw($customer_id, $entry_id=FALSE) {

		$ts = new Timesheet($this->timesheets,$this->customers);
		$entries = $ts->getEntries($customer_id);
		$ts->close();
		unset( $ts);

//print_r($entries);

		$this->control['ts_entries']->clear();

		foreach ( $entries as $idx => $dat ) {
			$row_dat = array( $dat['id'], $dat[1], $dat['start'], trim($dat[3]) );
			$this->control['ts_entries']->append($row_dat);
		}

		if ( $customer_id ) {
			// Make this customer selected as well
//			$this->control['ts_customers']->set_selected('id',$customer_id);
		}

		if ( $entry_id ) {
			$this->control['ts_entries']->set_selected('id',$entry_id);
		}

		$this->listview_drawn['entries'] = TRUE;

	}





	function disable($control) {
		$control = strtolower($control);
//echo "==>$control\n";

		$this->control[$control]->set_enabled(FALSE);	
	}
	
	function enable($control) {
		$control = strtolower($control);
//echo "-->$control\n";
		$this->control[$control]->set_enabled(TRUE);	
	}
	

	function enable_customer($customer_id) {
		// Enable all controls for a selected customer

		$this->enable('TS_NEW');
		$this->enable('TS_EDIT');
		$this->enable('TS_DELETE');
		$this->enable('TS_CUSTOMER2');
		$this->enable('TS_ENTRIES');


		$ts = new Customers($this->customers);
		$name = $ts->getCustomerName($customer_id);
		$company = $ts->getCustomerCompany($customer_id);
		$ts->close();
		unset($ts);

		$this->cust_name=$name.', '.$company;
		$this->show_project();

	}


	function enable_report_list() {
		$this->enable( 'TS_REPORT_LIST' );
	}

	function enable_reports() {
		$this->enable( 'TS_REPORT_LIST');
		$this->enable( 'TS_START_LABEL' );
		$this->enable( 'TS_END_LABEL' );
		$this->enable('TS_DATES_TODAY');
		$this->enable('TS_DATES_MNTH');
		$this->enable( 'TS_START_DATE');
		$this->enable( 'TS_END_DATE' );
		$this->visible( 'TS_START_DATE' );
		$this->visible( 'TS_END_DATE' );
		$this->enable( 'TS_PDF_REPORT' );
	}


	function text($control,$text) {
		$control = strtolower($control);
		$this->control[$control]->set_text($text);	
	}
	function set_text($control,$text) {
		$control = strtolower($control);
//echo "[-->$control]\n";
		$this->control[$control]->set_text($text);	
	}


	function get_text($control) {
		$control = strtolower($control);
//echo "[==>$control]\n";
		return($this->control[$control]->get_text());	
	}


	
	function get_position() {

	}


	function restore_position() {

	}


	function command_line($argv) {

		// Dropped file - don't start app, pass to add_file instead
		$dropped_file = trim($argv[1]);

		log::debug('argv[1]:'.$argv[1]);
		log::debug('argv[2]:'.$argv[2]);

		$path_parts = pathinfo($dropped_file);
		$ext = trim(strtolower($path_parts['extension']));

		$ext_not_capture = array('rds','rdl','rdc','rdr');

		if ( $dropped_file <> '' && $dropped_file <> 'autostart' ) {
			if ( $argv[2] == 'clicked' || in_array($ext,$ext_not_capture)  ) {

				// Double clicked file from extension associations
				log::write('Clicked file : '.$dropped_file);
				$this->clicked_file($dropped_file);			

			}
			else {
				log::write('Dropped file : '.$dropped_file);
				$this->capture($dropped_file);
			}
		}

	}

	/**
	*	Import an settings from the manager program
	*	Look for a ini file in the same location as the timesheet database file with the same name
	*	@param	
	*	@return	
	*	
	*/
	function manager_settings() {
	
		$cust_buttons = $this->glade->get_widget('customer_buttons');
		$proj_buttons = $this->glade->get_widget('project_buttons');

		$cnf = new conf_timesheet(INIFILE);

		if ( trim($cnf->ini['TIMESHEET']['current']) == '' ) return;
		if ( ! file_exists($cnf->ini['TIMESHEET']['current']) ) return;

		// See if this timesheet is managed 
		$ts = new Timesheet($cnf->ini['TIMESHEET']['current'],$this->customers);
		if ( $ts->isManaged() ) {
			$cnf->set_value('MANAGER','managed',TRUE);		
			$cnf->set_value('MANAGER','worker',$ts->getWorker());		
			$cust_buttons->hide_all();
			$proj_buttons->hide_all();
		}
		else {
			$cnf->set_value('MANAGER','managed',FALSE);		
			$cnf->set_value('MANAGER','worker',0);		
			$cust_buttons->show_all();
			$proj_buttons->show_all();
		}

		$ts->close();
		unset($ts);

		$cnf->save_ini();

	}

	/**
	*	Generate the tools menu
	*	
	*	@param	
	*	@return	
	*	
	*/
	function menu() {

		$cnf = new conf_timesheet(INIFILE);

		$tools = $this->glade->get_widget('menu_tools');		// GtkMenuItem

//print_r($this->glade);
//print_r($tools);
//return;
//		$tools->set_submenu(NULL);		// clear existing

		$menu = new GtkMenu();


		for ($i = 1; $i <= 5; $i++) {
			$idx = 'tools_text_'.$i;
			$text = trim($cnf->ini['TIMESHEET'][$idx]);
			if ( $text <> '' ) {

//				$menu[] = array($this->tools_id + $i,$text,NULL);

				// Menu item
				$menu_item = new GtkMenuItem($text);
				$menu_item->set_visible(TRUE);
				$menu_item->connect('activate', array($this,'onToolSelected_'.$i));
				$menu->append($menu_item);

			}
		}
				
		$tools->set_submenu($menu);
	}


	/**
	*	Check for news updates from pikaia web site - spawn sysutils to do this so that we don't 'hang' with the blocking connection
	*	
	*	@param	
	*	@return	
	*	
	*/
	function news_check() {
	
		$opts = array(
					  'http'=>array('timeout'=>5)
					);
		
		$context = stream_context_create($opts);
	

		$raw = @file_get_contents('http://pikaia.co.nz/timesheet/news.php?ver='.VER, FALSE, $context);
		if ( ! $raw ) return;
		$news = unserialize(base64_decode($raw));

		$id = $news['id'];
		$time = $news['time'];
		$news = $news['content'];
		$release = $news['release'];

//		$news = sprintf("%s\n%s",$time,$news);
		$this->control['news']->set_text($news);	

		// Check id news has changed since last displayed
		$cnf = new conf_timesheet(INIFILE);
		$last_id = $cnf->ini['TIMESHEET']['news_id'];
		
		if ( $id > $last_id ) {

			// News has changed
			$cnf->set_value('TIMESHEET','news_id',$id);		
			$cnf->save_ini();
			
			// Bring to user attention
			platform::message_popup("There is some updated news about Tazu-Timesheets.\n\nClick on the Latest News tab to view.",'News Update');
			
		}


		return(TRUE);
		
	}


	function news_check_first() {
		$this->news_check();
		return(FALSE);		// Do once and then disable this timer
	}

	function open() {
		global $argv;

		$this->customers = platform::app_data('Tazu-Timesheet').'customers.db';
		
		$cnf = new conf_timesheet(INIFILE);
		$this->timesheets = trim($cnf->ini['TIMESHEET']['current']);
		if ( $this->timesheets == '' ) {
			$this->timesheets = platform::app_data('Tazu-Timesheet').'timesheets.db';
			$cnf->set_value('TIMESHEET','current',$this->timesheets);		
			$cnf->save_ini();
		}
		else {
			// possible move of app_data location contining a timesheet
			if ( ! file_exists($this->timesheets) ) {
					$new_timesheet = sprintf("%s%s",platform::app_data('Tazu-Timesheet'),basename($this->timesheets));
					if ( file_exists($new_timesheet) ) {
						$this->timesheets = $new_timesheet;
						$cnf->set_value('TIMESHEET','current',$this->timesheets);		
						$cnf->save_ini();
					}
			}
		}


		// Set up any branding
		if ( $cnf->ini['BRAND']['logo_32'] <> '' ) {
			$logo = $this->glade->get_widget('logo');
			$logo->set_from_file('resources/'.$cnf->ini['BRAND']['logo_32']);
		}

		if ( $cnf->ini['BRAND']['logo_tooltip'] <> '' ) {
/*
			$logo_button = $this->glade->get_widget('logo_button');
			$logo_eventbox = $this->glade->get_widget('logo_eventbox');
			
			$tooltips = new GtkTooltips(); 
			$tooltips->set_tip($logo_eventbox,$cnf->ini['BRAND']['logo_tooltip'] ); 
*/

			$logo_button = $this->glade->get_widget('logo_button');
			$logo_button->set_tooltip_text($cnf->ini['BRAND']['logo_tooltip']);
		}



		$this->manager_settings();		// Before we do anything, check for any settings updates from the manager.

		// Load the text translations
		$c = new settings(platform::app_data('Tazu-Timesheet').'config.db');
		$this->data_types = $c->getDataTypes();
		unset($c);

//print_r($this->xlate);		
//print_r($GLOBALS['xlate']);		



//		$this->timers();

		$this->init_window(APPSHORTNAME.' '.VER.'.'.BUILD);

		$this->add_control(new notebook($this->glade,'ts_tabs'));

		$this->add_control(new label($this->glade,'ts_new_lbl',$this->xlate));
		$this->add_control(new label($this->glade,'ts_edit_lbl',$this->xlate));
		$this->add_control(new label($this->glade,'ts_delete_lbl',$this->xlate));
		$this->add_control(new label($this->glade,'proj_new_lbl',$this->xlate));
		$this->add_control(new label($this->glade,'proj_edit_lbl',$this->xlate));
		$this->add_control(new label($this->glade,'proj_delete_lbl',$this->xlate));
		$this->add_control(new label($this->glade,'comment_lbl'));
		$this->add_control(new label($this->glade,'ts_entry_task_lbl'));
		$this->add_control(new label($this->glade,'substitution_lbl'));

		$this->add_control(new customer_grid($this->glade,'ts_customers',$this));
		$this->add_control(new project_grid($this->glade,'proj_list',$this));
		$this->add_control(new entries_grid($this->glade,'ts_entries',$this));
		$this->add_control(new report_grid($this->glade,'ts_report_list',$this));

		$this->add_control(new data_grid($this->glade,'session_data',$this));
		$this->add_control(new pushbutton($this->glade,'session_data_add'));
		$this->add_control(new pushbutton($this->glade,'session_data_edit'));
		$this->add_control(new pushbutton($this->glade,'session_data_delete'));

		$this->add_control(new label($this->glade,'ts_customer2'));

		$this->add_control(new pushbutton($this->glade,'ts_edit'));
		$this->add_control(new pushbutton($this->glade,'ts_new'));
		$this->add_control(new pushbutton($this->glade,'ts_delete'));
		$this->add_control(new pushbutton($this->glade,'ts_timer'));
		$this->add_control(new label($this->glade,'ts_timer_label'));
		$this->add_control(new pushbutton($this->glade,'ts_save_b'));
		$this->add_control(new pushbutton($this->glade,'ts_delete_b'));
		$this->add_control(new pushbutton($this->glade,'ts_start_prev'));
		$this->add_control(new pushbutton($this->glade,'ts_elapsed_now'));
		$this->add_control(new pushbutton($this->glade,'ts_add_session'));
		$this->add_control(new pushbutton($this->glade,'proj_new'));
		$this->add_control(new pushbutton($this->glade,'proj_edit'));
		$this->add_control(new pushbutton($this->glade,'proj_delete'));
		$this->add_control(new pushbutton($this->glade,'ts_dates_today'));
		$this->add_control(new pushbutton($this->glade,'ts_dates_mnth'));
		$this->add_control(new pushbutton($this->glade,'ts_pdf_report'));
		$this->add_control(new pushbutton($this->glade,'cnf_save'));
		$this->add_control(new pushbutton($this->glade,'fb_mail2'));

		$this->add_control(new textview($this->glade,'ts_comment_b'));
		$this->add_control(new textentry($this->glade,'ts_entry_date'));
		$this->add_control(new combo($this->glade,'ts_entry_task'));

		$this->add_control(new checkbox($this->glade,'ts_all_customers'));


		$this->add_control(new spinbutton($this->glade,'ts_hour_start'));
		$this->add_control(new spinbutton($this->glade,'ts_hour'));
		$this->add_control(new spinbutton($this->glade,'ts_min_start'));
		$this->add_control(new spinbutton($this->glade,'ts_min'));

		$this->add_control(new label($this->glade,'ts_start_label'));
		$this->add_control(new label($this->glade,'ts_end_label'));
		$this->add_control(new calendar($this->glade,'ts_start_date'));
		$this->add_control(new calendar($this->glade,'ts_end_date'));

		$this->add_control(new frame_blue($this->glade,'select_customer_frame'));
		$this->add_control(new label_blue($this->glade,'select_customer_frame_label',$this->xlate));   //#0058EE

		$this->add_control(new frame_blue($this->glade,'select_project_frame'));
		$this->add_control(new label_blue($this->glade,'select_project_frame_label',$this->xlate));   //#0058EE

		$this->add_control(new frame_blue($this->glade,'edit_sessions_frame'));
		$this->add_control(new label_blue($this->glade,'edit_sessions_frame_label'));   //#0058EE

		$this->add_control(new frame_blue($this->glade,'select_report_frame'));
		$this->add_control(new label_blue($this->glade,'select_report_frame_label'));   //#0058EE

		$this->add_control(new frame_blue($this->glade,'select_dates_frame'));
		$this->add_control(new label_blue($this->glade,'select_dates_frame_label'));   //#0058EE

		$this->add_control(new frame_blue($this->glade,'date_shortcuts_frame'));
		$this->add_control(new label_blue($this->glade,'date_shortcuts_frame_label'));   //#0058EE

		$this->add_control(new frame_blue($this->glade,'reports_frame'));
		$this->add_control(new label_blue($this->glade,'reports_frame_label'));   //#0058EE

		$this->add_control(new frame_blue($this->glade,'tools_menu_frame'));
		$this->add_control(new label_blue($this->glade,'tools_menu_frame_label'));   //#0058EE

		$this->add_control(new frame_blue($this->glade,'fully_functional_frame'));
		$this->add_control(new label_blue($this->glade,'fully_functional_frame_label'));   //#0058EE

		$this->add_control(new frame_blue($this->glade,'free_frame'));
		$this->add_control(new label_blue($this->glade,'free_frame_label'));   //#0058EE

		$this->add_control(new textentry($this->glade,'cnf_name'));
		$this->add_control(new textentry($this->glade,'cnf_1t'));
		$this->add_control(new textentry($this->glade,'cnf_2t'));
		$this->add_control(new textentry($this->glade,'cnf_3t'));
		$this->add_control(new textentry($this->glade,'cnf_4t'));
		$this->add_control(new textentry($this->glade,'cnf_5t'));
		$this->add_control(new textentry($this->glade,'cnf_1p'));
		$this->add_control(new textentry($this->glade,'cnf_2p'));
		$this->add_control(new textentry($this->glade,'cnf_3p'));
		$this->add_control(new textentry($this->glade,'cnf_4p'));
		$this->add_control(new textentry($this->glade,'cnf_5p'));
		$this->add_control(new textentry($this->glade,'cnf_1x'));
		$this->add_control(new textentry($this->glade,'cnf_2x'));
		$this->add_control(new textentry($this->glade,'cnf_3x'));
		$this->add_control(new textentry($this->glade,'cnf_4x'));
		$this->add_control(new textentry($this->glade,'cnf_5x'));

		$this->add_control(new textentry($this->glade,'cnf_time_offset'));


		$this->add_control(new textview($this->glade,'news'));

		$this->add_control(new statusbar($this->glade,'statusbar1'));
		$this->add_control(new statusbar($this->glade,'statusbar2'));
		
		$this->set_status($this->timesheets);
		
		
		$this->customer_list_draw();		// Fill customer list
		$this->ReportList();		// Fill report list


		$this->start_time = FALSE;

		// Initial state of controls
		$this->menu();				// tools menu
		$this->task_name='';
		$this->cust_name='';
		$this->show_project();
						
		$this->control['ts_comment_b']->set_text('');
		$this->control['session_data']->clear();
		$this->control['ts_hour_start']->widget->set_range(0,23);
		$this->control['ts_hour']->widget->set_range(0,23);
		$this->control['ts_min_start']->widget->set_range(0,59);
		$this->control['ts_min']->widget->set_range(0,59);
		$this->control['ts_timer_label']->set_text('<span foreground="black" weight="bold">Start</span>');

		$this->resetControls();
		$this->enable('TS_NEW');
		
		// restore previous selections
		$customer_id = $cnf->ini['TIMESHEET']['customer_id'];
		$task_id = $cnf->ini['TIMESHEET']['task_id'];
		$entry_id = $cnf->ini['TIMESHEET']['entry_id'];
		$data_id = $cnf->ini['TIMESHEET']['data_id'];


		if ( $customer_id <> '' ) {

			$this->enable('TS_CUSTOMERS');
			$this->customer_list_draw($customer_id);				// Fill customer list
			$this->onCustomerClicked();							// Action as if clicked

		}				

		if ( $task_id <> '' ) {

			$this->enable(PROJ_LIST);
			$this->project_list_draw($customer_id,$task_id);		// Fill project list
			$this->onProjectClicked();							// Action as if clicked

//wb_message_box(null,'projects done');

			$this->entry_list_draw($customer_id,$entry_id);			// Fill project list
			$this->onEntryClicked();								// Action as if clicked
				
		
		}				


		if ( $entry_id <> '' ) {

			$this->entry_list_draw($customer_id,$entry_id);			// Fill project list
			$this->onEntryClicked();								// Action as if clicked
			$this->session_data_draw($entry_id,$fata_id);				// Fill project list
		
		}				



		// Timer
		if ( $cnf->ini['TIMESHEET']['timer_running'] && $customer_id<> '' && $task_id<>'' && $entry_id<>'' ) {

			$this->timer_running = TRUE;
			
			$timer_last = $cnf->ini['TIMESHEET']['timer_last'];


			// Perhaps the timer is still running from yesterday
			$timer_last_day = date("Y-m-d",$timer_last);
			$today = date("Y-m-d",$this->time_offset(mktime()));
			if ( $timer_last_day < $today ) {

				$ts = new Timesheet($this->timesheets,$this->customers);
				
				if ( platform::yes_no("You have an active timer still running from before today.\n\nWould you like to continue it into today?","Active Timer!") ) {

					// Terminate the elapsed at midnight yesterday
					$now = $this->time_offset(mktime());
					$old_elapsed = $ts->getEntryElapsed($entry_id);
					$midnight = mktime(0,0,0,date('m',$this->time_offset(mktime())),date('d',$this->time_offset(mktime())),date('Y',$this->time_offset(mktime())));
					$elapsed = $old_elapsed + ($midnight-$timer_last);
					$ts->updateEntryElapsed($entry_id,$elapsed);


					// Start a new session for today
					$task_id = $ts->getEntryTask($entry_id);
					$comment = $ts->getEntryComment($entry_id);
					$cnf->ini['TIMESHEET']['timer_last'] = $midnight;

//wb_message_box(null,"Set timer last:".date("Y-m-d H:i:s",$midnight));

					
					$new_entry_id = $ts->addEntry($customer_id,$task_id,date("Y-m-d 00:00:00",$this->time_offset(mktime())),0,$comment);								
					$entry_id = $new_entry_id;
					
/*
$msg = sprintf("
Customer      : %s
Old Task ID   : %s
Old Elapsed   : %s
Elapsed       : %s
New Elapsed   : %s
Updated Entry : %s
New Entry     : %s
Now           : %s
Midnight      : %s
Last          : %s
",
$customer_id,
$task_id,
$ts->elapsed($old_elapsed),
$ts->elapsed($elapsed),
$ts->elapsed($now-$midnight),
$entry_id,
$new_entry_id,
date("Y-m-d H:i:s",$now),
date("Y-m-d H:i:s",$midnight),
date("Y-m-d H:i:s",$timer_last)
);

wb_message_box(null,$msg);
*/

				}
				else {
					$this->timer_running = FALSE;
					$cnf->ini[strtoupper($this->win_name)]['timer_last'] = FALSE;
					$cnf->ini[strtoupper($this->win_name)]['timer_running'] = FALSE;
					$cnf->save_ini();
				}
			

				$ts->close();
				unset($ts);
			}

			
			if ( $this->timer_running ) {			
				// Update displays
				$this->update_timer();
	
				// Timer buttons and display
				$this->display_timer_running();
			}
			else {
				$this->display_timer_stopped();
				
			}

		}
		

		// Initial sorts
		$this->control['ts_customers']->set_sort('name',TRUE);
		$this->control['proj_list']->set_sort('task_code',TRUE);
		$this->control['ts_entries']->set_sort('start',FALSE);
		$this->control['session_data']->set_sort('type',FALSE);

		// Config tab
		$this->populate_config(INIFILE);

	}



	function onAbout() {
		$cnf = new conf_timesheet(INIFILE);

		$ts = new Timesheet($this->timesheets,$this->customers);
		$db_ver = $ts->getDBVersion();
		unset($ts);
				


		$abt = new GtkAboutdialog;
		$abt->set_icon_from_file(PATH_RES.'app_icon_16.png');
		$abt->set_program_name(APPNAME);
		$abt->set_version(VERSION);
		
	    $pixbuf=GdkPixbuf::new_from_file(PATH_RES.'app_icon_32.png'); 
		$abt->set_logo($pixbuf);
		
		$abt->set_copyright('Mike Bennett. '.date('Y'));
		$abt->set_authors(
							array(
								'Mike Bennett <mike@kereru.com>',
							)
						);
		
		$comment = '';
		$comment .= "Personal time tracking and timesheets.\n";
		$comment .= "Database : ".$db_ver."\n";
		$comment .= "\n";
		$comment .= "\n";
		$comment .= sprintf("%s %s\n",platform::os(),platform::os_ver());

		$abt->set_comments($comment);
		$abt->set_website('http://pikaia.co.nz');
		
		$license = "
Tazu-Time is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.

Tazu-Time is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Tazu-Time.  If not, see <http://www.gnu.org/licenses/>
";

		$abt->set_license($license);

		$abt->run();		
		$abt->destroy();
		
	}
	

	/**
	*	Save changed to edited session
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onSave() {
	
		$customer_id = $this->selected_customer();
		$entry_id = $this->selected_entry();

		if ( ! $entry_id ) return;
						
		$elapsed = ($this->get_text('TS_HOUR')*3600)+($this->get_text('TS_MIN')*60);
											
		$ts = new Timesheet($this->timesheets,$this->customers);

		// Edited task
		$new_task_id = $this->control['ts_entry_task']->code();
		$this->control['proj_list']->set_selected('id',$new_task_id);
		$new_task_code = $this->control['proj_list']->get_selected('task_code');

		// Current start date
		$start_timestamp = $ts->getEntryStart($entry_id);
		$start_date = substr($start_timestamp,0,10);
		$start_time = substr($start_timestamp,11,8);
						
		// Edited start date
		$new_start_date = $this->get_text('TS_ENTRY_DATE');
		$parts = explode("/",$new_start_date);
		$dd_new = trim($parts[0]);
		$mm_new = trim($parts[1]);
		$yy_new = trim($parts[2]);

		if ( $dd_new <> '' && $mm_new <> '' && $yy_new <> '' ) {
			$dd_new = sprintf("%02d",$dd_new);
			$mm_new = sprintf("%02d",$mm_new);
			$yy_new = sprintf("%04d",$yy_new);
						
			if ( $yy_new < 100 ) $yy_new = sprintf("%04d",$yy_new+2000);

			$start_date = sprintf("%04d-%02d-%02d", $yy_new, $mm_new, $dd_new);
		}
						
	
		$start = $start_date.' '.sprintf("%02d:%02d:00",$this->get_text('TS_HOUR_START'),$this->get_text('TS_MIN_START'));

		$ts->updateEntryTask($entry_id,$new_task_id);
		$ts->updateEntryStart($entry_id,$start);
						
		$ts->updateEntryComment($entry_id,$this->get_text('TS_COMMENT_B'));
		$ts->updateEntryElapsed($entry_id,$elapsed);
		$elapsed = $ts->elapsed($elapsed);					// Display formatted
		$ts->close();
		unset( $ts );

		// Disable until changes made
		$this->disable('TS_SAVE_B');
						
		// Refresh diaplay
		$start = Timesheet::timestamp2unix($start);
		$start = Timesheet::day_time($start);
						
		$this->entry_list_draw($customer_id);
		$this->control['ts_entries']->set_selected('id',$entry_id);

	}
	

	/**
	*	All customer checkbox toggled
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onAllCustomers() {

		if ( $this->control['ts_all_customers']->is_checked() ) {
				// Checked - all
//				wb_set_selected( wb_get_control($this->win, TS_CUSTOMERS ) , null, false ); 
				$this->enable_report_list();
					
		}
		else {
			// Selected customer				
		}

	}
		

	function onBackup() {

		$cnf = new conf_timesheet(INIFILE);

		$last_path = trim($cnf->ini['TIMESHEET']['backup_path']);
		if ( $last_path == '' ) $last_path = "C:";			

		$filefilter = array(
								"Timesheet Data"	=> "*.db",
								"All files"			=> "*.*"
							);
	

		$filename = platform::file_save($last_path,'timesheet_'.date("Ymd_His",$this->time_offset(mktime())).'.db',$filefilter,'Backing up :'.$this->timesheets);

		if ( $filename ) {
			$last_path = dirname($filename);
			$timesheet_file = $this->timesheets;

			if ( copy($timesheet_file,$filename) ) {
				$cnf->set_value('TIMESHEET','backup_path',$last_path);		
				$cnf->save_ini();
			}
			else {
				platform::error_popup("Unable to backup to ".$filename,'Error!');								
			}
					
		}
	
	}

	/**
	*	Typing in the comment area
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onCommentTyping() {
		$this->enable('TS_SAVE_B');
	}
	



	/**
	*	Customer in customer list selected/clicked
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onCustomerClicked() {

		$cnf = new conf_timesheet(INIFILE);
		$customer_id = $this->control['ts_customers']->get_selected('id');
		
		if ( $customer_id ) {

			// Customer selected
					
			// Record last selected customer/project/entry
			$cnf->set_value('TIMESHEET','customer_id',$customer_id);		
			$cnf->set_value('TIMESHEET','task_id',FALSE);		
			$cnf->set_value('TIMESHEET','entry_id',FALSE);		
			$cnf->set_value('TIMESHEET','data_id',FALSE);		

		}
		else {
			// No selection
			// Record last selected customer/project/entry
			$cnf->set_value('TIMESHEET','customer_id',FALSE);		
			$cnf->set_value('TIMESHEET','task_id',FALSE);		
			$cnf->set_value('TIMESHEET','entry_id',FALSE);		
			$cnf->set_value('TIMESHEET','data_id',FALSE);		
		}

		$cnf->save_ini();

		$this->customers();
		$this->projects();
	}
		

	/**
	*	Session data clicked
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onDataClicked() {

		$cnf = new conf_timesheet(INIFILE);

		$data_id = $this->control['session_data']->get_selected('id');

		if ( $data_id ) {

			// Record last selected customer/project/entry
			$cnf->set_value('TIMESHEET','data_id',$data_id);		
					
		}
		else {
			// No selection
			// Record last selected customer/project/entry
			$cnf->set_value('TIMESHEET','data_id',FALSE);		
		}
		$cnf->save_ini();

//		$this->projects();
	}
	


	/**
	*	shortcut button to select todays date
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onDateToday() {
		$today = $this->time_offset(mktime());
		
		$this->control['ts_start_date']->widget->select_month(date("m",$today)-1,date("Y",$today));
		$this->control['ts_end_date']->widget->select_month(date("m",$today)-1,date("Y",$today));

		$this->control['ts_start_date']->set_day(date("d",$today));
		$this->control['ts_end_date']->set_day(date("d",$today));
		
//$this->control['ts_start_date']->widget->mark_day(date("d",$today));
//$this->control['ts_start_date']->widget->mark_day(date("d",$today));

	}
	
	/**
	*	shortcut button to select todays date
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onDateThisMth() {

		$first = strtotime(sprintf("%s/1/%s",date('m',$this->time_offset(mktime())),date('Y',$this->time_offset(mktime()))));
		$today = $this->time_offset(mktime());
		
		$this->control['ts_start_date']->widget->select_month(date("m",$first)-1,date("Y",$first));
		$this->control['ts_start_date']->set_day(date("d",$first));

		$this->control['ts_end_date']->widget->select_month(date("m",$today)-1,date("Y",$today));
		$this->control['ts_end_date']->set_day(date("d",$today));

	}
	

	/**
	*	Start day clicked
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onDayStartSelected() {
		$this->control['ts_start_date']->set_day(date("d",$first));	
	}
	
	/**
	*	End day clicked
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onDayEndSelected() {
	
	}
	
	


	function onProjectClicked() {

		$cnf = new conf_timesheet(INIFILE);

		$task_id = $this->control['proj_list']->get_selected('id');


				
		if ( $task_id ) {

			// Record last selected customer/project/entry
			$cnf->set_value('TIMESHEET','task_id',$task_id);		
			$cnf->set_value('TIMESHEET','entry_id',FALSE);		
			$cnf->set_value('TIMESHEET','data_id',FALSE);		
					
		}
		else {
			// No selection
			// Record last selected customer/project/entry
			$cnf->set_value('TIMESHEET','task_id',FALSE);		
			$cnf->set_value('TIMESHEET','entry_id',FALSE);		
			$cnf->set_value('TIMESHEET','data_id',FALSE);		
		}
		$cnf->save_ini();

		$this->projects();
	}
	
	/**
	*	onEditCustomer
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onEditCustomer() {


		// Selected customer
		$customer_id = $this->selected_customer();


		if ( $customer_id ) {
			$cust = new edit_customer('Edit Customer Details','new_container');
			$ok = $cust->edit($customer_id,$this->customers);
			
			// redraw the customer list
			if ( $ok ) $this->customer_list_draw();
		}
					
	
	}

	/**
	*	onEditProject
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onEditProject() {


		// Selected customer
		$customer_id = $this->selected_customer();
		$task_id = $this->selected_task();


		if ( $task_id ) {
			$proj = new edit_project('Edit Project Details','new_container');
			$ok = $proj->edit($customer_id,$task_id,$this->customers);
			
			// redraw the customer list
			if ( $ok ) $this->project_list_draw($customer_id,$task_id);
		}
					
	
	}

	/**
	*	onAddCustomer
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onAddCustomer() {

		$cust = new edit_customer('Edit Customer Details','new_container');
		$customer_id = $cust->edit(FALSE,$this->customers);
			
		// redraw the customer list
		if ( $customer_id ) $this->customer_list_draw($customer_id);
	
	}

	/**
	*	onAddProject
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onAddProject() {

		$customer_id = $this->selected_customer();

		$proj = new edit_project('Edit Project Details','new_container');
		$task_id = $proj->edit($customer_id,FALSE,$this->customers);
			
		// redraw the customer list
		if ( $task_id ) $this->project_list_draw($customer_id,$task_id);
	
	}


	/**
	*	onDeleteCustomer
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onDeleteCustomer() {


		// Selected customer
		$customer_id = $this->selected_customer();
		if ( ! $customer_id ) return;

						
        if(platform::yes_no(
        					settings::xlate('Are you sure that you want to delete this [[customer]] ?'), 
        					settings::xlate('Delete [customer]')
        					)) { 

			$ts = new Customers($this->customers);
			$ts->delCustomer($customer_id);
			$ts->close();
			unset( $ts );
							
			$this->customer_list_draw();
			$this->resetControls();
		}

	}

	/**
	*	onDeleteProject
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onDeleteProject() {


		// Selected customer
		$customer_id = $this->selected_customer();
		$task_id = $this->selected_task();
		if ( ! $task_id ) return;

						
        if(platform::yes_no("Are you sure that you want to delete this project ?", 'Delete Project')) { 

			$ts = new Customers($this->customers);
			$ts->delProject($task_id);
			$ts->close();
			unset( $ts );
							
			$this->project_list_draw($customer_id);
		}

	}


	/**
	*	Add a new timesheet entry
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onAddEntry() {

		$customer_id = $this->selected_customer();
		$customer_name = $this->control['ts_customers']->get_selected('name');

		$task_id = $this->selected_task();

		if ( (! $customer_id ) && (! $task_id) ) return;

		$ts = new Timesheet($this->timesheets,$this->customers);
		$entry_id = $ts->addEntry($customer_id,$task_id,date("Y-m-d H:i:s",$this->time_offset(mktime())),0,'');
		$ts->close();
		unset( $ts );

		// Refresh list from database
		$this->entry_list_draw($customer_id);
									
		// Pre-selected the added session
		$this->control['ts_entries']->set_selected('id',$entry_id);		
//		wb_set_selected(wb_get_control($this->tabs,TS_ENTRIES),0);
					
		// New comment
		$this->set_text(TS_COMMENT_B,'',$this->tabs);

				

	}




	/**
	*	delete a timesheet entry
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onDeleteEntry() {

		$entry_id = $this->selected_entry();

		if ( ! $entry_id ) {
			platform::error_popup("Select a timesheet session entry from the list.",'Oops!');								
			return;
		}			

        if(platform::yes_no("Are you sure that you want to delete this session entry ?", 'Delete Timesheet Session')) { 

			$ts = new Timesheet($this->timesheets,$this->customers);
			$ts->delEntry($entry_id);
			$ts->close();
			unset( $ts );
							
			// Selected customer
			$customer_id = $this->selected_customer();;
							
			// Refresh list from database
			$this->entry_list_draw($customer_id);

//			$this->disable('TS_ENTRY_TASK');
			$this->control['ts_entry_task']->clear();
			
			$this->disable('TS_ENTRY_DATE');
			$this->disable('TS_HOUR_START');
			$this->disable('TS_MIN_START');
							
			$this->disable('TS_HOUR');
			$this->disable('TS_MIN');
							
			$this->text('TS_ENTRY_DATE','');
			$this->text('TS_HOUR_START','');
			$this->text('TS_MIN_START','');

			$this->text('TS_HOUR','');
			$this->text('TS_MIN','');


			$this->text('TS_COMMENT_B','');
			$this->control['session_data']->clear();
			$this->disable('TS_COMMENT_B');
			$this->disable('session_data');
			$this->disable('session_data_add');
			$this->disable('session_data_edit');
			$this->disable('session_data_delete');

		}

	}



	function onEntryClicked() {

		$cnf = new conf_timesheet(INIFILE);

		$customer_id = $this->selected_customer();
		$entry_id = $this->selected_entry();

		if ( $entry_id ) {

			$ts = new Timesheet($this->timesheets,$this->customers);
			$comment = $ts->getEntryComment($entry_id);

			$start = $ts->getEntryStart($entry_id);
			$start_date = substr($start,0,10);
			$start = substr($start,11,8);			// Only want the start time
						
						
			// Task/Project
			$task_id = $ts->getEntryTask($entry_id);
			$this->project_list_selected($customer_id,$task_id);


			// Start Date
			$parts = explode('-',$start_date);
			$yy_start = $parts[0];
			$mm_start = $parts[1];
			$dd_start = $parts[2];
			$date = sprintf("%02d/%02d/%04d",$dd_start,$mm_start,$yy_start);

			// Start Time
			$parts = explode(':',$start);
			$hh_start = $parts[0];
			$mm_start = $parts[1];


			// Elapsed
			$elapsed = $ts->elapsed($ts->getEntryElapsed($entry_id));
			$parts = explode(':',$elapsed);
			$hh = $parts[0];
			$mm = $parts[1];

			$ts->close();
			unset( $ts );

			$this->enable('TS_COMMENT_B');
			$this->control['ts_comment_b']->set_text($comment);

			$this->enable('TS_ENTRY_TASK');
			$this->enable('TS_ENTRY_DATE');
			$this->enable('TS_HOUR_START');
			$this->enable('TS_MIN_START');
						
			// Allow the now button only on events for today
			if ( $start_date == date("Y-m-d",$this->time_offset(mktime())) ) {
				$this->enable('TS_START_PREV');
				$this->enable('TS_ELAPSED_NOW');
			}
			else {
				$this->disable('TS_START_PREV');
				$this->disable('TS_ELAPSED_NOW');
			}

			$this->enable('TS_TIMER');

			$this->enable('TS_HOUR');
			$this->enable('TS_MIN');
						
			$this->control['ts_entry_task']->set_combo($this->projects2combo($entry_id));
			$this->control['ts_entry_task']->refresh();

			$this->text('TS_ENTRY_DATE',$date);
			$this->text('TS_HOUR_START',$hh_start);
			$this->text('TS_MIN_START',$mm_start);

			$this->text('TS_HOUR',$hh);
			$this->text('TS_MIN',$mm);

			$this->disable('TS_SAVE_B');
			$this->enable('TS_DELETE_B');

			$this->session_data_draw($entry_id);
			$this->enable('session_data');
			$this->enable('session_data_add');
			$this->enable('session_data_edit');
			$this->enable('session_data_delete');
					
			// Record last selected customer/project/entry
			$cnf->set_value('TIMESHEET','entry_id',$entry_id);		
			$cnf->set_value('TIMESHEET','data_id',FALSE);		
			$cnf->save_ini();


		}
		else {

			$this->disable('TS_ENTRY_TASK');
			$this->disable('TS_ENTRY_DATE');
			$this->disable('TS_HOUR_START');
			$this->disable('TS_MIN_START');
						
			$this->disable('TS_HOUR');
			$this->disable('TS_MIN');
						
			$this->disable('TS_COMMENT_B');
			$this->text('TS_COMMENT_B', '');

			$this->disable('TS_TIMER');
			$this->disable('TS_SAVE_B');
			$this->disable('TS_DELETE_B');

			$this->disable('session_data');
			$this->session_data_draw(FALSE);
			$this->disable('session_data_add');
			$this->disable('session_data_edit');
			$this->disable('session_data_delete');
															
			// Record last selected customer/project/entry
			$cnf->set_value('TIMESHEET','entry_id',FALSE);		
			$cnf->set_value('TIMESHEET','data_id',FALSE);		
			$cnf->save_ini();

		}				
	
	}
	
	function onFeedback() {
	
		$body = sprintf("\n\nTazu-Timesheet Version:%s.%s\n",VER,BUILD);
	
		$cmd = sprintf("utils\MAPISend.exe");
		$params = sprintf("/E /S Tazu-Timesheet Program Feedback /A office@pikaia.co.nz /B %s",$body);
		platform::exec($cmd,$params);		
	}
	

	function onHelp() {
		$url = "http://pikaia.co.nz/timesheet/help.php";
		platform::exec($url);
	}
	

	/**
	*	Learn more about RocketDMS
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onLearnMore_rdms() {
		platform::exec('http://pikaia.co.nz/?id=dms&page=timesheet1');
	}



	/**
	*	Learn more about 31Mail
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onLearnMore_31mail() {
		platform::exec('http://31mail.pikaia.co.nz');
	}


	/**
	*	Logo button clicked
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onLogoClicked() {

		$cnf = new conf_timesheet(INIFILE);

		$url = 'http://pikaia.co.nz';
		if ( $cnf->ini['BRAND']['logo_url'] <> '' ) $url = $cnf->ini['BRAND']['logo_url'];

		platform::exec($url);
	
	}


	function onNew() {

		if ( $this->timer_running ) {
			platform::error_popup("Unable to comply. Stop running timer first.",'Error!');								
			return;
		}

		$cnf = new conf_timesheet(INIFILE);
		$last_path = dirname(trim($cnf->ini['TIMESHEET']['current']));
		if ( $last_path == '' ) $last_path = "C:";			

		$filefilter = array(
							"Timesheet Data"		=> "*.db",
							"All files"			=> "*.*"
							);
	

		$filename = platform::file_save($last_path,'.db',$filefilter,'New Timesheets File');


		if ( $filename ) {
			$this->timesheets = $filename;

			$cnf->set_value('TIMESHEET','current',$filename);		
			$cnf->save_ini();
										
			$this->customer_list_draw();		// Fill customer list
			$this->ReportList();		// Fill report list
					
			$this->task_name='';
			$this->cust_name='';
			$this->show_project();
									
			$this->text('TS_COMMENT_B','');
			
			$this->resetControls();
			$this->enable('TS_NEW');

			$this->set_status($this->timesheets);
							
		}	

	}


	/**
	*	Now button
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onNowButton() {

		// Set elapsed to be from the start until now
		$start_hh = $this->get_text('TS_HOUR_START');
		$start_mm = $this->get_text('TS_MIN_START');
		$start = ($start_hh*60)+$start_mm;

		$end = (date("H",$this->time_offset(mktime()))*60)+date("i",$this->time_offset(mktime()));					

		$elapsed = $end-$start;
		$elapsed_hh = floor( $elapsed / 60 );					
		$elapsed_mm = fmod( $elapsed , 60 );

		$this->set_text('TS_HOUR',$elapsed_hh);
		$this->set_text('TS_MIN',$elapsed_mm);
	
	}

	/**
	*	Open a timesheet file
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onOpen() {

		if ( $this->timer_running ) {
			platform::error_popup("Unable to comply. Stop running timer first.",'Error!');								
			return;
		}

		$cnf = new conf_timesheet(INIFILE);

		$last_path = dirname(trim($cnf->ini['TIMESHEET']['current']));
		$last_file = basename(trim($cnf->ini['TIMESHEET']['current']));

		if ( $last_path == '' ) $last_path = "C:";			

		$filefilter = array(
							"Timesheet Data"		=> "*.db",
							"All files"			=> "*.*"
							);
	

		$filename = platform::file_select($last_path,$last_file,$filefilter);
		
		if ( $filename ) {
			// Exists ?
			if ( ! file_exists($filename) ) {
				platform::error_popup("File does not exist :".$filename,'Oops!');								
				return;
			}
					
			// Timesheet data?

//wb_message_box(null,"Checking version:".$filename);

			$ts = new Timesheet($filename,$this->customers);
			$db_ver = $ts->db_ver;
			$ts->close();
			unset($ts);

			if ( $db_ver ) {
	
				$this->timesheets = $filename;
	
				$cnf->set_value('TIMESHEET','current',$filename);		
				$cnf->save_ini();
	
				$this->customer_list_draw();		// Fill customer list
				$this->ReportList();				// Fill report list
						
				$this->task_name='';
				$this->cust_name='';
				$this->show_project();
										
				$this->resetControls();
				$this->enable('TS_NEW');

				$this->manager_settings();	
	
				$this->set_status($filename);
			}
			else {
				platform::error_popup("Does not appear to be timesheet data :".$filename,'Error!');								
				return;
			}
							
		}
	}

	/**
	*	end of previous button
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onPrevButton() {

		// Set start time to be at the end of the previously recordd session


		// previously recorded session
		$selected_entry_id = $this->selected_entry();
		$customer_id = $this->selected_customer();

		$ts = new Timesheet($this->timesheets,$this->customers);
		$prev_entry_id = $ts->getPreviousEntry($customer_id,$selected_entry_id);


		if ( ! $prev_entry_id ) return;

		// Is the previous entry on the same day
		if ( $ts->getEntryStartDay($selected_entry_id) <> $ts->getEntryStartDay($prev_entry_id) ) {
			return;
		}



		$new_start = $ts->getEntryEnd($prev_entry_id);
		$new_start_hh = substr($new_start,11,2);
		$new_start_mm = substr($new_start,14,2);

		$this->set_text('TS_HOUR_START',$new_start_hh);
		$this->set_text('TS_MIN_START',$new_start_mm);

		$ts->close();
		unset( $ts);
		
	}


	/**
	*	report list clicked
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onReportClicked() {


				$report_id = $this->selected_report();

				if ( $report_id >= 0) {
					$this->enable_reports();
				}
	
	}


	/**
	*	Menu item to purge old timesheet entries
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onPurge_6() {
		$this->onPurge(6);
	}
	function onPurge_12() {
		$this->onPurge(12);
	}
	function onPurge_18() {
		$this->onPurge(18);
	}
	function onPurge($months=18) {
	
		// date months ago
		$cutoff = date("Y-m-d",mktime(0, 0, 0, date("m",$this->time_offset(mktime()))-$months, date("d",$this->time_offset(mktime())),   date("Y",$this->time_offset(mktime()))));

		$cutoff_display = date("d M Y",mktime(0, 0, 0, date("m",$this->time_offset(mktime()))-$months, date("d",$this->time_offset(mktime())),   date("Y",$this->time_offset(mktime()))));
		

        if(platform::yes_no("Have you backed up!!\n\nAre you sure that you want to delete all entries before\n<b>$cutoff_display</b> ?", 'Purge Old Timesheets')) { 

			$ts = new Timesheet($this->timesheets,$this->customers);
			$ts->purgeEntries($cutoff);
			$ts->close();
			unset( $ts );

			$entry = $this->selected_entry();
			$this->entry_list_draw($this->selected_customer(),$this->selected_entry());
//			$this->session_data_draw($entry);

		}	

	

	}


	function onSaveAs() {

		if ( $this->timer_running ) {
			platform::error_popup("Unable to comply. Stop running timer first.",'Error!');								
			return;;
		}

		$cnf = new conf_timesheet(INIFILE);

		$last_path = trim($cnf->ini['TIMESHEET']['current']);
		if ( $last_path == '' ) $last_path = "C:";			

		$filefilter = array(
								"Timesheet Data"	=> "*.db",
								"All files"			=> "*.*"
							);
	

//				$filename = wb_sys_dlg_save ($this->win, 'Save As',$filefilter, $last_path,null,'db');

//echo "last:$last_path\n";

		$filename = platform::file_save(dirname($last_path),basename($last_path),$filefilter,'Save As');


		if ( $filename ) {
			$timesheet_file = $this->timesheets;

			if ( file_exists($filename) ) {
				// Check if the selected destination is an already managed timesheet
				// If so, don't allow to overwrite.
				$ts = new Timesheet($filename,$this->customers);
				if ( $ts->isManaged() ) {
					platform::error_popup("Unable to save to ".$filename,'Error!');								
					return;				
				}
				$ts->close();
				unset($ts);
			}

			if ( copy($timesheet_file,$filename) ) {
				$this->timesheets = $filename;
				$this->set_status($this->timesheets);


				$cnf->set_value('TIMESHEET','current',$filename);		
				$cnf->save_ini();
		
			}
			else {
				platform::error_popup("Unable to save to ".$filename,'Error!');								
			}

					
		}
	
	}

	/**
	*	Save configuration
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onSaveConfig() {

		$cnf = new conf_timesheet(INIFILE);

		$cnf->set_value('TIMESHEET','name',$this->get_text('CNF_NAME'));

		$cnf->set_value('TIMESHEET','tools_text_1',$this->get_text('CNF_1T'));
		$cnf->set_value('TIMESHEET','tools_prog_1',$this->get_text('CNF_1P'));
		$cnf->set_value('TIMESHEET','tools_param_1',$this->get_text('CNF_1X'));

		$cnf->set_value('TIMESHEET','tools_text_2',$this->get_text('CNF_2T'));
		$cnf->set_value('TIMESHEET','tools_prog_2',$this->get_text('CNF_2P'));
		$cnf->set_value('TIMESHEET','tools_param_2',$this->get_text('CNF_2X'));

		$cnf->set_value('TIMESHEET','tools_text_3',$this->get_text('CNF_3T'));
		$cnf->set_value('TIMESHEET','tools_prog_3',$this->get_text('CNF_3P'));
		$cnf->set_value('TIMESHEET','tools_param_3',$this->get_text('CNF_3X'));

		$cnf->set_value('TIMESHEET','tools_text_4',$this->get_text('CNF_4T'));
		$cnf->set_value('TIMESHEET','tools_prog_4',$this->get_text('CNF_4P'));
		$cnf->set_value('TIMESHEET','tools_param_4',$this->get_text('CNF_4X'));

		$cnf->set_value('TIMESHEET','tools_text_5',$this->get_text('CNF_5T'));
		$cnf->set_value('TIMESHEET','tools_prog_5',$this->get_text('CNF_5P'));
		$cnf->set_value('TIMESHEET','tools_param_5',$this->get_text('CNF_5X'));

		$cnf->set_value('TIMESHEET','time_offset',$this->get_text('cnf_time_offset'));

		$cnf->save_ini();

		// Re-generate menus for possible Tools changes
		$this->menu();
	
	}
	

	function onTabClicked() {
	
	}

	/**
	*	Start/Timer button clicked
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onTimerButton() {
		$cnf = new conf_timesheet(INIFILE);

										
		if ( $this->timer_running ) {

			$this->win->set_title(APPSHORTNAME.' '.VER.'.'.BUILD);

			// Click Stop
			$this->control['ts_timer_label']->set_text('<span foreground="black" weight="bold">Start</span>');
			$this->timer_running = FALSE;
			
			// Allow tabs
			$this->control['ts_tabs']->widget->set_show_tabs(TRUE);
			
			$this->display_timer_stopped();				


			// Record this timer in case of program close.
			$cnf->set_value('TIMESHEET','timer_running',$this->timer_running);		
			$cnf->set_value('TIMESHEET','timer_last',FALSE);		
			$cnf->save_ini();

		}
		else {
			// Click Start
			// Can run the timer against a selected entry for today

			$customer_id = $this->selected_customer();
			$entry_id = $this->selected_entry();


			if ( $customer_id && $entry_id ) {

				// Have a selected entry, can only add to it if it for today
				$today = date("Y-m-d",$this->time_offset(mktime()));
				$ts = new Timesheet($this->timesheets,$this->customers);
				$entry_day = $ts->getEntryStartDay($entry_id);

				if ( $entry_day <> $today ) {

					// Entry is for a previous day but we want to continue recording time against it.
					// Duplicate that entry for today
								
					$task_id = $ts->getEntryTask($entry_id);
					$comment = $ts->getEntryComment($entry_id);

					$new_entry_id = $ts->addEntry($customer_id,$task_id,date("Y-m-d H:i:s",$this->time_offset(mktime())),0,$comment);								

					if ( $new_entry_id ) {
									
						// insert succeeded - refresh entry list
						$this->entry_list_draw($customer_id);
									
						// Make top one selected
						$this->control['ts_entries']->set_selected('id',$new_entry_id);
					}
				}

				$ts->close();
				unset($ts);						
			}


			$entry_id = $this->selected_entry();

			if ( $entry_id ) {
				$this->timer_running = TRUE;
				$this->control['ts_tabs']->widget->set_show_tabs(FALSE);
				$this->display_timer_running();					

				// Record this timer in case of program close.
				$cnf->set_value('TIMESHEET','timer_running',$this->timer_running);		
				$cnf->set_value('TIMESHEET','timer_last',$this->time_offset(mktime()));		
				$cnf->save_ini();

			}


		}				
				
				
	}


	/**
	*	Config tab, select a program
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onSelectProg_1() {
		$this->onSelectProg(1);
	}
	function onSelectProg_2() {
		$this->onSelectProg(2);
	}
	function onSelectProg_3() {
		$this->onSelectProg(3);
	}
	function onSelectProg_4() {
		$this->onSelectProg(4);
	}
	function onSelectProg_5() {
		$this->onSelectProg(5);
	}
	function onSelectProg($n) {

		$filefilter = array(
								"Executable (.exe)"	=> "*.exe",
								"Executable (.com)"	=> "*.com",
								"Batch File (.bat)"	=> "*.bat",
								"All files"			=> "*.*"
							);

		$prog = $this->control['cnf_'.$n.'p']->get_text();
		$prog = platform::file_select(dirname($prog),basename($prog),$filefilter,'Select Program');

		if ( $prog ) {
			$this->control['cnf_'.$n.'p']->set_text($prog);
		}

	}

	/**
	*	Add new session data line
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onSessionDataAdd() {

		$entry_id = $this->selected_entry();

		$dat = new edit_session_dat('Edit Session Data','new_container');
		$dat_id = $dat->edit($entry_id,FALSE);

//echo "added [$dat_id]\n";


		// redraw the customer list
		if ( $dat_id ) $this->session_data_draw($entry_id,$dat_id);
	
	}
	
	/**
	*	Edit a session data line
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onSessionDataEdit() {

		$entry_id = $this->selected_entry();
		$data_id = $this->selected_data();
		if ( ! $data_id ) return;


		$dat = new edit_session_dat('Edit Session Data','new_container');
		$dat_id = $dat->edit($entry_id,$data_id);

//echo "added [$dat_id]\n";


		// redraw the customer list
		if ( $dat_id ) $this->session_data_draw($entry_id,$dat_id);
	
	}
	
	/**
	*	Delete a session data line
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onSessionDataDelete() {

		$entry_id = $this->selected_entry();
		$data_id = $this->selected_data();
		if ( ! $data_id ) return;

						
        if(platform::yes_no("Are you sure that you want to delete this data ?", 'Delete Attached Session Data')) { 

			$ts = new Timesheet($this->timesheets,$this->customers);
			$ts->delDat($data_id);
			$ts->close();
			unset( $ts );
							
			$this->session_data_draw($entry_id);
//			$this->resetControls();
		}

	
	}
	

	/**
	*	Tools menu item selected
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onToolSelected_1() {
		$this->onToolSelected(1);
	}
	function onToolSelected_2() {
		$this->onToolSelected(2);
	}
	function onToolSelected_3() {
		$this->onToolSelected(3);
	}
	function onToolSelected_4() {
		$this->onToolSelected(4);
	}
	function onToolSelected_5() {
		$this->onToolSelected(5);
	}

	function onToolSelected($n) {
		$cnf = new conf_timesheet(INIFILE);

		$prog = $cnf->ini['TIMESHEET']['tools_prog_'.$n];		
		$param = $cnf->ini['TIMESHEET']['tools_param_'.$n];		


		$ts = new Timesheet($this->timesheets,$this->customers);
		$cs = new Customers($this->customers);

		$customer_id = $this->selected_customer();
		if ( ! $customer_id ) {
			$customer_name = '';
		}
		else {		
			$customer_name = $cs->getCustomerName($customer_id);
		}
		
		
		$prog = str_replace('[c]',$customer_name,$prog);
		$prog = str_replace('[C]',$customer_name,$prog);
		$param = str_replace('[c]',$customer_name,$param);
		$param = str_replace('[C]',$customer_name,$param);
		
		$task_id = $this->selected_task();
		if ( ! $task_id ) {
			$task_code = '';
		}
		else {
			$task_code = $cs->getProjectCode($task_id);		
		}
		
		$prog = str_replace('[p]',$task_code,$prog);
		$prog = str_replace('[P]',$task_code,$prog);
		$param = str_replace('[p]',$task_code,$param);
		$param = str_replace('[P]',$task_code,$param);
		
		
		
		$email_bill = $cs->getCustomerEmailBill($customer_id);

		$prog = str_replace('[e]',$email_bill,$prog);
		$prog = str_replace('[E]',$email_bill,$prog);
		$param = str_replace('[e]',$email_bill,$param);
		$param = str_replace('[E]',$email_bill,$param);
		

//wb_message_box(null,$prog.' '.$param);

		$ts->close();
		unset($ts);


//		wb_message_box(null,$prog,$param);

		if ( file_exists($prog) ) {
//			@wb_exec($prog,$param);
			platform::exec($prog,$param);
		}
		else {
			platform::error_popup("File/Path does not exist :\n".$prog,'Oops!');								
		}
	
	}
	
	
	/**
	*	Populate with ver 3 config
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onVer3Config() {

		if ( file_exists('C:/Program Files/Pikaia/timesheet.ini') ) {
			$this->populate_config('C:/Program Files/Pikaia/timesheet.ini');
			platform::message_popup("Click SAVE to keep these settings.\n\nWhen done you may delete the old file:\n\nC:/Program Files/Pikaia/timesheet.ini ",'Tazu-Timesheets Config Upgrade');		
		}
		else {
			platform::message_popup('No version 3 configuration found.','Tazu-Timesheets Config Upgrade');		
		}
	
	}

	
	/**
	*	Generate and view report
	*	
	*	@param	
	*	@return	
	*	
	*/
	function onViewReport() {

		$sel_report = $this->selected_report();
		
//echo "[$sel_report]\n";

		if ( ! $sel_report ) return;

		// Selected customer
		if ( $this->control['ts_all_customers']->is_checked() ) {
			// Checked - all
			$customer_id = FALSE;		// All
		}
		else {
			$customer_id = $this->selected_customer();
			$customer_name = $this->control['ts_customers']->get_selected('name');
		}					

		// Selected task
		$task_id = $this->selected_task();

		// Have we satisfied pre-requisites for chosen report
		$rp = new Reports($this->timesheets,$this->customers);
		$reports = $rp->reports;
		unset($rp);
					
//print_r($reports);
//return;

		if ( $reports[$sel_report]['customer'] && (! $this->selected_customer() ) ) {
			platform::error_popup("You need to select a customer for this report.",'Oops!');								
			return;
		}
					
		if ( $reports[$sel_report]['task'] && (! $this->selected_task() )) {
			platform::error_popup("You need to select a project for this report.",'Oops!');								
			return;
		}
					

		$start_date = $this->control['ts_start_date']->get_date();
		$end_date = $this->control['ts_end_date']->get_date();
		
		if ( $end_date < $start_date ) $end_date = $start_date;

//		$gl->timesheet_report = new ts_report($sel_report,$customer_id,$task_id,$start_date,$end_date);

		$cnf = new conf_timesheet(INIFILE);
	
		// Temp file name
		$tempfile = platform::temp().'spk_report.htm';

		// Generate report
		$rp = new Reports($cnf->ini['TIMESHEET']['current'],$this->customers);
		$rp->name = $cnf->ini['TIMESHEET']['name'];					// Company name for reports

		// CSV reports
		if ( $rp->reports[$sel_report]['csv'] ) {
			// Select a CSV file location to save to

			$last_path = trim($cnf->ini['TIMESHEET']['csv_path']);
			if ( $last_path == '' ) $last_path = "C:";			

			$filefilter = array(
									"Timesheet Data"	=> "*.csv",
									"All files"			=> "*.*"
								);
		
	
			$filename = platform::file_save($last_path,'entries.csv',$filefilter,'CSV Data Export');
	
			if ( $filename ) {
				$last_path = dirname($filename);
				$cnf->set_value('TIMESHEET','csv_path',$last_path);		
				$cnf->save_ini();
			}

		}
		
		$html = $rp->report($sel_report,$customer_id,$task_id,$start_date,$end_date,$filename);

//print_r($ts->reports);
//echo "[$html]";

		// HTML reports
		if ( $rp->reports[$sel_report]['html'] ) {
			// Temp save

			file_put_contents($tempfile,$html);
			platform::exec($tempfile);
		}

		// CSV reports
		if ( $rp->reports[$sel_report]['csv'] ) {


		}


		unset( $rp);


			
	}
	
	/**
	*	Populate config tab
	*	
	*	@param	
	*	@return	
	*	
	*/
	function populate_config($inifile) {

		$cnf = new conf_timesheet($inifile);


		$this->set_text('CNF_NAME',$cnf->ini['TIMESHEET']['name']);


		$this->set_text('CNF_1T',$cnf->ini['TIMESHEET']['tools_text_1']);
		$this->set_text('CNF_1P',$cnf->ini['TIMESHEET']['tools_prog_1']);
		$this->set_text('CNF_1X',$cnf->ini['TIMESHEET']['tools_param_1']);

		$this->set_text('CNF_2T',$cnf->ini['TIMESHEET']['tools_text_2']);
		$this->set_text('CNF_2P',$cnf->ini['TIMESHEET']['tools_prog_2']);
		$this->set_text('CNF_2X',$cnf->ini['TIMESHEET']['tools_param_2']);

		$this->set_text('CNF_3T',$cnf->ini['TIMESHEET']['tools_text_3']);
		$this->set_text('CNF_3P',$cnf->ini['TIMESHEET']['tools_prog_3']);
		$this->set_text('CNF_3X',$cnf->ini['TIMESHEET']['tools_param_3']);

		$this->set_text('CNF_4T',$cnf->ini['TIMESHEET']['tools_text_4']);
		$this->set_text('CNF_4P',$cnf->ini['TIMESHEET']['tools_prog_4']);
		$this->set_text('CNF_4X',$cnf->ini['TIMESHEET']['tools_param_4']);

		$this->set_text('CNF_5T',$cnf->ini['TIMESHEET']['tools_text_5']);
		$this->set_text('CNF_5P',$cnf->ini['TIMESHEET']['tools_prog_5']);
		$this->set_text('CNF_5X',$cnf->ini['TIMESHEET']['tools_param_5']);

		$this->set_text('cnf_time_offset',$cnf->ini['TIMESHEET']['time_offset']);
	
	}	

	function projects2combo($entry_id) {
	
		$ts = new Timesheet($this->timesheets,$this->customers);
		$cs = new Customers($this->customers);
		
		// Current task_id for this entry
		$task_id = $ts->getEntryTask($entry_id);		
	
		$customer_id = $this->selected_customer();
		if ( ! $customer_id ) {
			unset($ts);
			return(FALSE);
		}
	
	
		$i = 0;
		
		// Selected at top
		$task_code = $cs->getProjectCode($task_id);
		$task_description = $cs->getProjectDescription($task_id);
		$combo = array();
		$combo[$i]['label'] = sprintf("%s : %s",$task_code,$task_description);
		$combo[$i]['code'] = $task_id;
		
		// All others
		$task_list = $ts->getProjects($customer_id);
		
		foreach ( $task_list as $idx => $dat ) {

			$task_code1 = $dat['task_code'];
			if ( $task_code <> $task_code1 ) {
				$i++;
				$task_description1 = $dat['task'];

//				$combo[$task_code1]['label'] = sprintf("%s : %s",$task_code1,$task_description1);
//				$combo[$task_code1]['code'] = $dat['id'];

				$combo[$i]['label'] = sprintf("%s : %s",$task_code1,$task_description1);
				$combo[$i]['code'] = $dat['id'];

			}
		}
		
		unset($ts);

		return($combo);

	}
	
/*
	function combo2project($selected) {
		$parts = explode(':',$selected);
		$task_code = trim($parts[0]);
		
		// Find the internal task_id of this code.
		$ts = new Timesheet($this->timesheets);

		$task_id = $ts->getProjectId($task_code);
			
		unset($ts);
		return( $task_id);
	}
*/	

	function ReportList() {

		$r = new Reports($this->timesheets,$this->customers);
		$reports = $r->getReports();
		unset( $r);

		$this->control['ts_report_list']->clear();

		foreach ( $reports as $id => $name ) {
			$row_dat = array( $id, $name );
			$this->control['ts_report_list']->append($row_dat);
		}
		
	}

	function resetControls() {
		// Initial state of controls

		// Customers
		$this->enable('TS_NEW');					// Always enabled
		$this->disable('TS_EDIT');
		$this->disable('TS_DELETE');

		// Timer
		$this->disable('TS_TIMER');

		// Time Sheet

		$this->disable('TS_ADD_SESSION');

		$this->control['ts_entries']->clear();
		$this->control['session_data']->clear();

		$this->disable('ts_customer2');

		$this->disable('ts_entries');
		$this->disable('session_data');
		$this->disable('session_data_add');
		$this->disable('session_data_edit');
		$this->disable('session_data_delete');
		$this->disable('ts_comment_b');
		$this->disable('TS_SAVE_B');
		$this->disable('TS_DELETE_B');

		$this->disable('TS_ENTRY_TASK');
		$this->disable('TS_ENTRY_DATE');

		$this->disable('TS_HOUR_START');
		$this->disable('TS_MIN_START');

		$this->disable('TS_START_PREV');
		$this->disable('TS_ELAPSED_NOW');

		$this->disable('TS_HOUR');
		$this->disable('TS_MIN');

		$this->control['ts_entry_task']->clear();
		$this->control['ts_entry_date']->set_text('');
		$this->control['ts_hour_start']->set_text('');
		$this->control['ts_min_start']->set_text('');
		$this->control['ts_hour']->set_text('');
		$this->control['ts_min']->set_text('');
		$this->control['ts_comment_b']->set_text('');
		$this->control['session_data']->clear('');

		$this->task_name='';
		$this->cust_name='';
		$this->show_project();
								
		// Reports
		$this->disable('ts_report_list');

		$this->disable('TS_DATES_TODAY');
		$this->disable('TS_DATES_MNTH');

		$this->disable('TS_START_DATE');
		$this->disable('TS_END_DATE');
		$this->control['ts_start_date']->set_visible('FALSE');
		$this->control['ts_end_date']->set_visible('FALSE');
		
		$this->disable('TS_START_LABEL');
		$this->disable('TS_END_LABEL');
		$this->disable('TS_PDF_REPORT');
		
		// Project/Tasks List
		$this->control['proj_list']->clear();
//		$this->disable(PROJ_FRAME);
		$this->disable('proj_list');
		$this->disable('PROJ_EDIT');
		$this->disable('PROJ_DELETE');
		$this->disable('PROJ_NEW');
		
	}


	function selected_customer() {
		$customer_id = $this->control['ts_customers']->get_selected('id');
		return( $customer_id );
	}
	
	function selected_task() {
		$task_id = $this->control['proj_list']->get_selected('id');
		return( $task_id );
	}

	function selected_entry() {
		$entry_id = $this->control['ts_entries']->get_selected('id');
		return( $entry_id );
	}
	
	function selected_report() {
		$entry_id = $this->control['ts_report_list']->get_selected('id');
		return( $entry_id );
	}
	
	function selected_data() {
		$data_id = $this->control['session_data']->get_selected('id');
		return( $data_id );
	}
	


	/**
	*	Populate the session data grid
	*	
	*	@param	
	*	@return	
	*	
	*/
	function session_data_draw($entry_id,$data_id=FALSE) {

		$ts = new Timesheet($this->timesheets,$this->customers);
		$data = $ts->getData($entry_id);
		$ts->close();
		unset( $ts);

		$c = new settings(platform::app_data('Tazu-Timesheet').'config.db');
		$data_types = $c->getDataTypes();
		unset($c);


//print_r($data_types);

		$this->control['session_data']->clear();

//print_r($data);

		foreach ( $data as $idx => $dat ) {
			$row_dat = array( $dat['id'], $data_types[$dat['type']]['name'], $dat['value'], $data_types[$dat['type']]['unit'], $dat['comment'] );
			$this->control['session_data']->append($row_dat);
		}


		$this->session_data_selected( $data_id );


	}

	function session_data_selected($data_id) {

		if ( $data_id ) {
			$this->control['session_data']->set_selected('id',$data_id);
		}

//		$this->listview_drawn['projects'] = TRUE;

	}

	function show_project() {
		$display = sprintf("<b>%s %s %s</b>",$this->cust_name, ($this->task_name<>'')?':':'' , $this->task_name );
		$this->control['ts_customer2']->set_text(sprintf("<span foreground=\"#0058EE\">%s</span>",$display));		
	}	

	function timers() {

		/* Clock update  */
		Gtk::timeout_add(500, array($this, 'clock'));

		/* Clock flasher  */
		Gtk::timeout_add(1000, array($this, 'clock_flasher'));


		/* update auto timer */
		Gtk::timeout_add(60000, array($this, 'update_timer'));

		// First check for news after 1st minute .....
		Gtk::timeout_add(1*60*1000, array($this, 'news_check_first'));
		
		// ... and from then on check for news every hour
		Gtk::timeout_add(60*60*1000, array($this, 'news_check'));


		/* Automatic session timer  */
//		Gtk::timeout_add(1000, array($this, 'auto_timer'));

	}


	/**
	*	Apply the time offset
	*	
	*	@param	
	*	@return	
	*	
	*/
	function time_offset($time) {

		$cnf = new conf_timesheet(INIFILE);
		$offset = $cnf->ini['TIMESHEET']['time_offset'];
	
		if ( ! is_numeric($offset) ) return($time);
		
		return($time + $offset);
	
	}


	function update_timer() {

		$cnf = new conf_timesheet(INIFILE);

		if ( $this->timer_running ) {
					
			// Time of last timer update
			$timer_last = $cnf->ini['TIMESHEET']['timer_last'];

			$now = $this->time_offset(mktime());

			if ( $timer_last && $timer_last < $now-90 ) {
				// Only if we have somehow missed the last minute tick. 
				// Prevents rounding error on standard 1 minute ticks 
				// Increment by the amount of time since last done. round up.
				$secs = $now - $timer_last;							
				$timer_increment = ceil($secs/60);
			}
			else {
				// Increment by 1 minute
				$timer_increment = 1;
			}
					
			// Update and save the time stored against tis task. Add 60 seconds to the elapsed
			$hh = $this->get_text('TS_HOUR');
			$mm = $this->get_text('TS_MIN');

			// lazy way of doing the maths
			for ($i = 1; $i <= $timer_increment; $i++) {
				$mm = $mm+1;
				if ( $mm >=60 ) {
					$hh++;
					$mm = 0;
				}
			}
						
			$this->set_text('TS_HOUR',$hh);
			$this->set_text('TS_MIN',$mm);

			// Save the update
			$entry_id = $this->selected_entry();
			if ( $entry_id ) {
				$elapsed = ($this->get_text('TS_HOUR')*3600)+($this->get_text('TS_MIN')*60);
				$ts = new Timesheet($this->timesheets,$this->customers);
				$ts->updateEntryElapsed($entry_id,$elapsed);							
				$elapsed = $ts->elapsed($elapsed);					// Display formatted
				$ts->close();
				unset($ts);

				// Update the entry list display
				$entry_id = $this->selected_entry();

				// Record the time of last increment in case program closed with timer running
				$cnf->set_value('TIMESHEET','timer_last',$this->time_offset(mktime()));		
				$cnf->save_ini();

			}
		}

		return(TRUE);
		
	}	
	


}



?>